package com.xwt.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.xwt.web.dao.AuthorityRepository;
import com.xwt.web.dao.UserRepository;
import com.xwt.web.entity.Authority;
import com.xwt.web.entity.User;
import com.xwt.web.jwt.JwtConfigProperty;
import com.xwt.web.jwt.JwtUtil;

/**
 * JWT验证过滤器，放在用户密码过滤器之前 解析token中用户信息，并赋予上下文
 * 
 * @author Administrator
 *
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private JwtConfigProperty jwtConfig;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private UserRepository userDao;
	@Autowired
	private AuthorityRepository authorityDao;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String authHeader = request.getHeader(this.jwtConfig.getHeader());
		String tokenHead = this.jwtConfig.getTokenHead();
		if (authHeader != null && authHeader.startsWith(tokenHead)) {
			String authToken = authHeader.substring(tokenHead.length());
			try {
				if (jwtUtil.validateToken(authToken)) {
				String username= jwtUtil.getSubjectFromToken(authToken);
				User user = userDao.findByUsername(username);
				List<Authority> list = authorityDao.findByUsername(username);
				UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
						user.getUsername(), user.getPassword(), list);
				authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
				SecurityContextHolder.getContext().setAuthentication(authentication);
			}
			}catch (Exception e) {
				logger.info("token格式有误");
			}
		}
		filterChain.doFilter(request, response);

	}

}
